from opcua import Client
import pandas as pd
from common.config import opcUaConfig as Config
import time

def connect():
    userName = '' if pd.isna(Config.userName) else Config.userName
    passwd = '' if pd.isna(Config.passwd) else Config.passwd

    # print("connect to: ", "opc.tcp://"+Config.serverIP)
    # # PLC地址
    client = Client("opc.tcp://"+Config.serverIP)
    client.set_user(userName)
    client.set_password(passwd)

    connected = False
    while connected == False:
        try:
            client.connect()
            connected = True
        except Exception as exp:
            print(f"connect Exception : [{exp}]")
            connected = False
            time.sleep(Config.reconnectSpan)
            continue

    print("connect say : Wonderful, I connected to the server !!")

    root = client.get_root_node()
    objects = client.get_objects_node()

    # 测试服务器节点分布！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
    commonNodes = objects.get_children()[1].get_children()
    # PLC 节点分布
    # commonNodes = objects.get_children()[2].get_children()[0].get_children()

    print("-----------------连接-------------------------------")
    return commonNodes


def getData1(commonNodes):  # （多久读一次，读哪些节点的数据）
    data1 = {}
    data1[Config.WindSpeed] = [commonNodes[Config.windSpeedNodeID_R].get_value()]
    data1[Config.WindDirection] = [commonNodes[Config.windDirectionNodeID_R].get_value()]
    data1[Config.ActPower] = [commonNodes[Config.actPowerNodeID_R].get_value()]
    data1[Config.RotateSpeed] = [commonNodes[Config.generatorSpeedNodeID_R].get_value()]
    data1[Config.PitchAngle] = [commonNodes[Config.pitchAngleNodeID_R].get_value()]
    data1["GeneratorTorq"] = [commonNodes[Config.generatorTorqNodeID_R].get_value()]
    data1["TempAmbient"] = [commonNodes[Config.tempAmbientNodeID_R].get_value()]
    data1["WindDirectionToNorth"] = [commonNodes[Config.windDirectionToNorthNodeID_R].get_value()]
    data1["DataEffectiveFlag"] = [commonNodes[Config.dataEffectiveFlagNodeID_R].get_value()]
    data1["HeartBeatFlagServer"] = [commonNodes[Config.heartBeatFlagServerNodeID_R].get_value()]
    return data1

def getDatam(commonNodes):
    datam = pd.DataFrame(columns=[Config.WindSpeed, Config.WindDirection, Config.ActPower, Config.RotateSpeed, Config.PitchAngle,'GeneratorTorq',
                                        'TempAmbient', 'WindDirectionToNorth', 'DataEffectiveFlag', 'HeartBeatFlagServer'])
    span = Config.datamSpan*Config.data1Span
    for i in range(span):
        data1 = getData1(commonNodes)
        datam = pd.concat([datam, pd.DataFrame(data1)])
        if (len(datam)>Config.repeatNum) and (len(datam["HeartBeatFlagServer"][-5:-1].drop_duplicates()) == 1):
            print("-----------------------心跳数据没有变reconncet-----------------------------------")
            raise Exception("conncet error")
        time.sleep(Config.data1Span)
    return datam